#!/usr/local/bin/tclsh
##############################################################################
# Taho jabber bot.
# LICENSE:
#  This code comes with ABSOLUTELY NO WARRANTY.
#  This program is free software; you can redistribute it
#  and/or modify it under the terms of the GNU General Public
#  License as published by the Free Software Foundation;
#  either version 2 of the License, or (at your option) any
#  later version.
#
#  This program is distributed in the hope that it will be
#  useful, but WITHOUT ANY WARRANTY; without even the implied
#  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#  PURPOSE.  See the GNU General Public License for more
#  details. (http://www.gnu.org/copyleft/library.txt)
#
# Copyright (C) 2009, Vladimir Chernyavski
# kellinby(at)gmail(dot)com
##############################################################################
set platform $tcl_platform(platform)
if {"$platform"=="windows"} {
set rootdir [file dirname [info script]]
} elseif {"$platform"=="unix"} {
set rootdir [pwd]
}
set dir $rootdir
set debug_lvls {tkabber Dir_to_source plugins message chat filetransfer disco iq \
login pep presence pubsub register roster userinfo custom ssj INFO code hook comand cmd:run}
proc debugmsg {level msg} {
    global debug_lvls

    if {[lsearch -exact $debug_lvls $level] >= 0} {
	puts "$level: $msg"
    }
}

proc fullpath {args} {
    global rootdir
    return [eval file join $rootdir $args]
}

proc load_source {args} {
    set fullpath [eval fullpath $args]

    debugmsg tkabber "Loading $fullpath"
    uplevel #0 [list source $fullpath]
}
load_source tclxml pkgIndex.tcl
load_source xmpp pkgIndex.tcl
package require msgcat
::msgcat::mclocale ru

proc srcdir {dir} {
global rootdir
	set tmp [file join $rootdir $dir]
	debugmsg Dir_to_source "$dir"
	foreach file [glob -nocomplain -directory $tmp *.tcl] {
		load_source $file
	}
}
set configdir $rootdir

proc get_snapshot {changelog} {
    set snapshot ""
    if {[catch { open $changelog } fd]} {
	return $snapshot
    }
    while {[gets $fd line] >= 0} {
	if {[regexp {(\d\d\d\d)-(\d\d)-(\d\d)} $line -> year month day]} {
	    set snapshot "-$year$month$day"
	    break
	}
    }
    close $fd
    return $snapshot
}
set bot(version) "0.5-svn[get_snapshot [fullpath change.log]]"
set toolkit_version "Tcl/Tk [info patchlevel]"
proc rescmd {id res ls} {
    puts "RESULT: $id $res $ls"
}

proc quit {{status 0}} {
    hook::run quit_hook
    catch { bind $::ifacetk::mf <Destroy> {} }
    destroy .
    exit $status
}
load_source tkabber hooks.tcl
hook::add quit_hook logout 10
hook::add quit_hook {
    foreach chan [file channels] {
        if {[string first sock $chan] != -1} {
            catch { close $chan } res
            debugmsg tkabber "closed $chan '$res'"
        }
    }
} 100
load_source tkabber default.tcl
hook::add postload_hook postload
hook::add finload_hook finload

load_source tkabber trans.tcl
::trans::load [file join $rootdir trans]
::msgcat::mcload [file join $rootdir msgs]
foreach pr [::msgcat::mcpreferences] {
    set f [file join $rootdir msgs $pr.rc]
    if {[file exists $f]} {
	option readfile $f
	break
    }
}
unset pr f
if {[catch { package require Tclx }]} {
    load_source tkabber Tclx.tcl
}
package require xmpp
package require xmpp::delay

load_source tkabber xmppmime.tcl

foreach {opt val} $argv {
    switch -- $opt {
	-mime       {set mime_file $val}
	-user       {set loginconf(user) $val}
	-password   {set loginconf(password) $val}
	-resource   {set loginconf(resource) $val}
	-port       {set loginconf(port) $val}
	-autologin  {set autologin $val}
	-chat       {xmppmime::send_event [list chat $val]}
	-message    {xmppmime::send_event [list message $val]}
	-conference {xmppmime::send_event [list groupchat $val]}
	-splash     {set show_splash_window $val}
    }
}

if {[info exists mime_file]} {
    xmppmime::load $mime_file
}

load_source tkabber idna.tcl
load_source tkabber namespaces.tcl
load_source tkabber custom.tcl

load_source tkabber utils.tcl
load_source tkabber plugins.tcl

load_source tkabber presence.tcl
load_source tkabber iq.tcl
load_source tkabber disco.tcl
load_source tkabber roster.tcl

load_source tkabber messages.tcl
load_source tkabber chats.tcl
load_source tkabber joingrdialog.tcl
load_source tkabber muc.tcl
load_source tkabber login.tcl
load_source tkabber userinfo.tcl
load_source tkabber datagathering.tcl


load_source tkabber register.tcl
load_source tkabber si.tcl



load_source tkabber gpgme.tcl
load_source tkabber pubsub.tcl
load_source tkabber pep.tcl

if {[file exists [file join $configdir bot.cfg]]} {
    source [file join $configdir bot.cfg]
}

srcdir taho
srcdir plugins
debugmsg INFO ".........................................."
#load_source tplugins pkgIndex.tcl


hook::run postload_hook
hook::run finload_hook

#package require xmpp::full
set xlib [::xmpp::new -messagecommand    bot:message    \
				  -presencecommand   client:presence   \
				  -iqcommand         bot:iq         \
				  -disconnectcommand bot:disconnect \
				  -errorcommand      bot:error      \
				  -logcommand        bot:log]

::xmpp::connect $xlib $bot(host) $bot(port)
::xmpp::openStream $xlib $bot(host) -version 1.0
::xmpp::sasl::auth $xlib -username $bot(userid) \
						-password $bot(password) \
						-resource $bot(resource) \

# Send initial presence
# Если закоментировать то бот будет работать не посылая презенсов в ростер.
lappend statusdesc(online) 1234
lappend userstatus online
set textstatus [::msgcat::mc "default room status" $bot(version)]
send_first_presence $xlib
set defaultnick $bot(nick)

disco::new $xlib

# Start event loop
vwait forever